package com.allwees.core.common.i18n;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Locale;

/**
 * 提供获取 Message Source 的 message
 *
 * @author: Xiao Xuezhi
 * @email: index.xiao@foxmail.com
 * @date: 2020/12/16 15:57
 * @since: 1.0.0
 */
@Component
public class MessageSourceProvider {

    @Autowired
    private MessageSource messageSource;

    private Locale defaultLocale;

    @Value("${spring.profiles.active}")
    private String profile;

    @PostConstruct
    public void init() {
        if ("ae".equals(profile) || "sa".equals(profile) || "san".equals(profile) || "aen".equals(profile)) {
            defaultLocale = new Locale("ar");
        } else {
            defaultLocale = Locale.US;
        }
    }

    public String getMessage(String code, Object[] args) {
        return messageSource.getMessage(code, args, defaultLocale);
    }

    public String getMessageOrDefault(String code, String defaultMessage, Object[] args) {
        return messageSource.getMessage(code, args, defaultMessage, defaultLocale);
    }

    public String getMessage(Locale locale, String code, Object[] args) {
        return messageSource.getMessage(code, args, locale);
    }

    public String getMessageOrDefault(Locale locale, String code, String defaultMessage, Object[] args) {
        return messageSource.getMessage(code, args, defaultMessage, locale);
    }
}
